package com.starzy.mr;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * @Author: starzy https://www.cnblogs.com/starzy
 * @Description:
 * @Date: Created in 10:27 2020/12/15
 */
public class WordCountMR {
    /**
     * 统计单词个数: wordCount,并且使用Combiner
     *
     * 使用Combiner要注意以下三项注意：
     *
     * 1、Combiner和Reducer的区别在于运行的位置：Combiner是在每一个MapTask所在的节点运行，Reducer是接收全局所有Mapper的输出结果
     * 2、Combiner的输入key-value的类型就是Mapper组件输出的key-value的类型，Combiner的输出key-value要跟reducer的输入key-value类型要对应起来
     * 3、Combiner的使用要非常谨慎，因为Combiner在MapReduce过程中是可选的组件，可能调用也可能不调用，可能调一次也可能调多次，
     * 所以：Combiner使用的原则是：有或没有都不能影响业务逻辑，都不能影响最终结果
     */
    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        // 指定hdfs相关的参数
        Configuration conf = new Configuration();
        conf.set("fs.defaultFS", "hdfs://node01:9000");
        System.setProperty("HADOOP_USER_NAME", "root");

        Job job = Job.getInstance(conf);
        // 设置jar包所在路径
        job.setJarByClass(WordCountMR.class);

        // 指定mapper类和reducer类
        job.setMapperClass(WordCountMapper.class);
        job.setReducerClass(WordCountReducer.class);
        job.setCombinerClass(WordCountConbiner.class);

        // 指定maptask的输出类型， 如果maptask的输出key-value类型和reduceTask的key-value类型一致。那么可以不写
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(LongWritable.class);

        // 指定reducetask的输出类型
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(LongWritable.class);

        // 本地路径
//		Path inputPath = new Path("D:/data/words/input");
//		Path outputPath = new Path("D:/data/words/output");
        Path inputPath = new Path(args[0]);
        Path outputPath = new Path(args[1]);

        FileSystem fs = FileSystem.get(conf);
        if(fs.exists(outputPath)){
            fs.delete(outputPath, true);
        }
        FileInputFormat.setInputPaths(job, inputPath);
        FileOutputFormat.setOutputPath(job, outputPath);

        // 最后提交任务
        boolean waitForCompletion = job.waitForCompletion(true);
        System.exit(waitForCompletion?0:1);
    }

    private static class WordCountMapper extends Mapper<LongWritable, Text,Text,LongWritable>{
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String[] words = value.toString().split(" ");
            for (String word : words) {
                context.write(new Text(word),new LongWritable(1));
            }
        }
    }

    private static class WordCountConbiner extends Reducer<Text,LongWritable,Text,LongWritable>{
        @Override
        protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
            long sum = 0;
            for (LongWritable value : values) {
                sum += value.get();
            }
            context.write(key,new LongWritable(sum));
        }
    }

    private static class WordCountReducer extends Reducer<Text,LongWritable,Text,LongWritable>{
        @Override
        protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
            long sum = 0;
            for (LongWritable value : values) {
                sum += value.get();
            }
            context.write(key,new LongWritable(sum));
        }
    }
}
